#!/bin/bash
#前提：安装好JDK8 或JDK11
# 说明：如有需要请在以下修改配置
# 修改JVM配置请在/data/tools/elasticsearch/config/jvm.options
# 安装好以后，切换用户elasticsearch，不能使用root启动
# 最后执行以下命令，是否安装成功 curl http://127.0.0.1:9200
# 如果一定要以root执行，则执行以下命令： ./ elasticsearch -Des.insecure.allow.root=true
version="7.6.1"

mkdir -p /data/tools
cd /data/tools

package_url="https://mirrors.huaweicloud.com/elasticsearch/${version}/elasticsearch-${version}-linux-x86_64.tar.gz"

wget -c ${package_url} || exit 1

tar zxvf elasticsearch-${version}-linux-x86_64.tar.gz

ln -sf elasticsearch-${version} elasticsearch

# 解决问题：[1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
echo vm.max_map_count=262144 >>/etc/sysctl.conf

sysctl -p

echo "* soft nofile 65536" >>/etc/security/limits.conf

echo "* hard nofile 131072" >>/etc/security/limits.conf

echo "Set data path: /data/elasticsearch/data"
mkdir -p /data/data/elasticsearch/data

echo "Set logs path: /data/elasticsearch/logs"
mkdir -p /data/logs/elasticsearch/logs

echo "Add user elasticsearch!"
useradd elasticsearch

chown -v elasticsearch:elasticsearch /data/tools/elasticsearch /data/tools/elasticsearch-${version} /data/data/elasticsearch/ -R

echo "Setting es config file, Config content:"
rm -rf /data/tools/elasticsearch/config/bak_elasticsearch.yml
mv /data/tools/elasticsearch/config/elasticsearch.yml /data/tools/elasticsearch/config/bak_elasticsearch.yml
sudo tee /data/tools/elasticsearch/config/elasticsearch.yml <<-'EOF'
#集群名称
cluster.name: elasticsearch 	
#节点名称
node.name: node-1 
#数据和日志的存储目录
path.data: /data/data/elasticsearch/data
path.logs: /data/data/elasticsearch/logs
#设置绑定的ip，设置为0.0.0.0以后就可以让任何计算机节点访问到了
network.host: 0.0.0.0
#端口
http.port: 9200 
#设置在集群中的所有节点名称，这个节点名称就是之前所修改的，当然你也可以采用默认的也行，目前是单机，放入一个节点即可
cluster.initial_master_nodes: ["node-1"]
EOF

# 运行脚本时出现了问题，es版本7，./elasticsearch-env: line 126: syntax error near unexpected token `<’。解决方案：bash 3.0后，shell中加入了新的符号"<<<" ，将报错的位置的双< < 修改 <<<
sed -i 's/set -e -o pipefail/set +o posix/g'  /data/tools/elasticsearch/bin/elasticsearch-env


echo 'note:kibana install success! Start kibana by executing the following command'
echo 'su elasticsearch'
echo 'sh /data/tools/elasticsearch/bin/elasticsearch -d'
echo 'Test is start success:  curl http://127.0.0.1:9200'

